package com.mifengs.mall.ui.main;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.entity.HomeInfo;
import com.mifengs.mall.entity.HomeResponseBean;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.entity.TabBean;
import com.mifengs.mall.netWork.NetWork;

import java.util.ArrayList;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lihaoqi on 2018/4/17.
 */

public class NewHomePresenter implements NewHomeContract.Presenter{

    private NewHomeContract.View mView;

    public NewHomePresenter(NewHomeContract.View mView) {
        this.mView = mView;
    }

    public static final String TAG = "NewHomePresenter";


    @Override
    public void getClassifyData() {
//        try {
//            ArrayList<TabBean> tabBeanList = SampleApplicationLike.getInstance().getCacheHelper().getAsSerializable(TAG);
//            if(tabBeanList!=null){
//                mView.setClassifyData(tabBeanList);
//            }
//        }catch (Exception e){
//
//        }
        mView.showLoading();
        NetWork.getHomeDataApi().getHomeData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBean<HomeResponseBean>>bindToLife())
                .subscribe(new Observer<ResponseBean<HomeResponseBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        mView.hideLoading();
                        mView.reload(false);

                    }

                    @Override
                    public void onNext(ResponseBean<HomeResponseBean> responseBean) {
                        mView.hideLoading();
                        mView.reload(true);
                        if (responseBean.getStatus().equals(Constant.SUCCESS_CODE)){
                            HomeInfo homeInfo = responseBean.getParamer().getAppPageDecorateDto();
                            ArrayList<TabBean> tabBeanList = (ArrayList<TabBean>) homeInfo.getAppTabDecorateDtoList();
                            mView.setClassifyData(tabBeanList);
                            MallApplication.getInstance().getCacheHelper().put(TAG,tabBeanList);
                            PreferenceUtils.saveSearchUrl(mView.getContext(),homeInfo.getSearchUrl());
                        }else{
                            mView.showLongToast(responseBean.getInfo());
                        }
                    }
                });
    }


}
